public class Main {
    public static void main(String[] args) {
        int[] nums={3,2,6,5,0,3};
        Main main = new Main();
        System.out.println(main.maxProfit(2, nums));
        main.maxProfit(nums);
    }
    //买卖股票的最佳时机 IV
    public int maxProfit(int k, int[] prices) {
        int n = prices.length;
        int INT=0x3f3f3f3f;
        k=Math.min(k,n/2);

        int[][] f=new int[n][k+1];
        int[][] g=new int[n][k+1];
        for (int j = 0; j <= k; j++) {
            f[0][j]=g[0][j]=-INT;
        }
        f[0][0]=-prices[0];
        g[0][0]=0;
        for (int i = 1; i < n; i++) {
            for (int j = 0; j <= k; j++) {
                f[i][j]=Math.max(f[i-1][j], g[i-1][j]-prices[i]);
                g[i][j]=g[i-1][j];
                if(j-1>=0){
                    g[i][j]=Math.max(g[i-1][j],f[i-1][j-1]+prices[i]);
                }
            }
        }
        int ret=-0x3f3f3f3f;
        for(int j=0;j<=k;j++){
            ret=Math.max(ret,g[n-1][j]);
        }
        return ret;
    }

    //买卖股票的最佳时机 III
    public int maxProfit(int[] prices) {
        int m = prices.length;
        if (m == 0) return 0;
        int[][] f = new int[m][3];
        int[][] g = new int[m][3];
        f[0][0] = -prices[0];
        f[0][1] = f[0][2] = -0x3f3f3f3f;
        g[0][1] = g[0][2] = -0x3f3f3f3f;
        for (int i = 1; i < m; i++) {
            for (int j = 0; j < 3; j++) {
                f[i][j] = Math.max(f[i - 1][j], g[i - 1][j] - prices[i]);
                g[i][j] = g[i - 1][j];
                if (j - 1 >= 0) {
                    g[i][j] = Math.max(g[i - 1][j], f[i - 1][j - 1] + prices[i]);
                }
            }

        }
        return Math.max(Math.max(g[m - 1][0], g[m - 1][1]), g[m - 1][2]);
    }


    //最大子数组和
    public int maxSubArray(int[] nums) {
        int n=nums.length;
        if(n==0) return 0;
        int[] dp=new int[n+1];
        int ret=Integer.MIN_VALUE;
        dp[0]=0;
        for(int i=1;i<=n;i++){
            dp[i]=Math.max(nums[i-1],dp[i-1]+nums[i-1]);
            ret=Math.max(ret,dp[i]);
        }
        return ret;
    }
}